/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
// 递归
class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root == nullptr) {
            return 0;
        } else {
            int leftDepth = minDepth(root->left);
            int rightDepth = minDepth(root->right);

            return min(leftDepth, rightDepth) == 0 ? max(leftDepth, rightDepth) + 1 : min(leftDepth, rightDepth) + 1;
        }
    }
};

// 迭代
class Solution {
public:
    int minDepth(TreeNode* root) {
        queue<TreeNode*> queue;
        int depth = 0;
        if(root != nullptr) queue.push(root);

        while(queue.empty() == false) {
            int size = queue.size();
            depth = depth + 1;
            for(int i = 0; i < size; ++i){
                TreeNode* node = queue.front();
                queue.pop();

                if(node->left == nullptr && node->right == nullptr){
                    return depth;
                }

                if(node->left) queue.push(node->left);
                if(node->right) queue.push(node->right);
            }
        }

        return depth;
    }
};
